#include <malloc.h>
#include "teacher.h"
#include "teacher_index.h"
/* 结构体数据存放内存区指针 */
static p_teacher teachers = NULL;
/* 结构体索引指针内存存放区的指针 */
static tsize *p_teachers = NULL;
/* 当前数据存放区的实际长度 */
static int length = 0;
/* 实际使用的数据存放区的最后一个区块的位置 */
static int position = -1;
/* 结构体单个内存区域的大小 */
static int t_size = sizeof(teacher);
/* 结构体索引单个内存区域的大小 */
static int p_t_size = sizeof(tsize);
/* 申请内存的方法 */
static p_teacher resize(tsize size);
/* 往最末尾添加一条记录 */
int push(p_teacher p)
{
	if(NULL == resize(position + 2))
	{
		return 0;
	}
	else
	{
		tsize index = get_position(position);
		teachers[index] = *p;
		p_teachers[++position] = index;
		return 1;
	}
}
/* 修改结构体容器内存 */
p_teacher resize(tsize size)
{
	if(length < size)
	{
		void *temp1 = realloc(teachers,size * t_size);
		if(temp1 == NULL)
		{
			return (p_teacher)NULL;
		}
		void *temp2 = realloc(p_teachers,size * p_t_size);
		if(temp2 == NULL)
		{
			return (p_teacher)NULL;
		}	
		teachers = temp1;
		p_teachers = temp2;
		length = size;
		return teachers;
	}
	else
	{
		return teachers;
	}
}
/* 往指定位置添加一条记录 */
int insert(p_teacher p,tsize index)
{
	if(NULL == resize(t_size * (position + 2)) || position < 0)
	{
		return 0;
	}
	else
	{
		for(int i = ++position;i > index;i--)
		{
			p_teachers[i] = p_teachers[i - 1];
		}
		tsize teacher_index = get_position(position);
		teachers[teacher_index] = *p;
		p_teachers[index] = teacher_index;
		return 1;
	}
}
/* 删除指定位置的记录 */
int delete_by_index(tsize index)
{
	if(position < 0)
	{
		return 0;
	}
	else
	{
		// 记录废弃不用的数据下表
		push_index(p_teachers[index]);
		for(int i = index;i < position;i++)
		{
			p_teachers[i] = p_teachers[i + 1];
		}
		position--;
		return 1;
	}
}
/* 根据传递的排序函数对数据进行排序 */
int sort(int (*c)(p_teacher,p_teacher))
{
	tsize temp_index = 0;
	teacher temp_teacher;
	for(int i = 0;i < position;i++)
	{
		temp_index = i;
		for(int j = i + 1;j <= position;j++)
		{
			if(c(teachers + p_teachers[temp_index],teachers + p_teachers[j]) > 0)
			{
				temp_index = j;
			}
		}
		if(temp_index != i)
		{
			p_teachers[temp_index] = p_teachers[temp_index] ^ p_teachers[i];
			p_teachers[i] = p_teachers[temp_index] ^ p_teachers[i];
			p_teachers[temp_index] = p_teachers[temp_index] ^ p_teachers[i];
		}
	}
}
/* 输出列表所有的记录 */
void print_all()
{
	printf("id\tname\tsubject\n");
	for(int i = 0;i <= position;i++)
	{
		printf("%d\t%s\t%s\n",teachers[p_teachers[i]].id,teachers[p_teachers[i]].name,teachers[p_teachers[i]].subject);
	}
}
/* 清空现有的记录 */
void clean_teachers()
{
	free(teachers);
	teachers = NULL;
	p_teachers = NULL;
	length = 0;
	position = -1;
	free_index();
}
